package service;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import model.NewsRecent;

public class PutCache {
	public static void putCacheNews(NewsRecent news,String nameCache,int size)
	{
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		if(cache.containsKey(nameCache))
		{
			ArrayList<NewsRecent> lastupdate = (ArrayList<NewsRecent>)cache.get(nameCache);
        	if(lastupdate.size()>size)
        	{
        		lastupdate.remove(0);
        	}
        	int check=0;
        	for (int i = 0; i < lastupdate.size(); i++) {
				if(lastupdate.get(i).getTitle().equals(news.getTitle()))
					check=1;
			}
        	if(check==0)
        		lastupdate.add(news);
        	cache.put(nameCache, lastupdate);
		} else {
			ArrayList<NewsRecent> lastupdate = new ArrayList<NewsRecent>();
        	if(!lastupdate.contains(news))
        		lastupdate.add(news);
        	cache.put(nameCache, lastupdate);
		}
	}
	public static void putCacheList(String name,String nameCache,int num)
	{
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
		   e.printStackTrace();
		   
		}
    	if(cache.containsKey(nameCache))
		{
			ArrayList<String> siteview = (ArrayList<String>)cache.get(nameCache);
        	if(siteview.size()>num)
        	{
        		siteview.remove(0);
        	}
        	if(!siteview.contains(name))
        		siteview.add(name);
        	cache.put(nameCache, siteview);
		} else {
			ArrayList<String> siteview = new ArrayList<String>();
        	if(!siteview.contains(name))
        		siteview.add(name);
        	cache.put(nameCache, siteview);
		}
	}
	
	@SuppressWarnings("unchecked")
	public static ArrayList<String> getCacheList(String nameCache)
	{
		ArrayList<String>  list = new ArrayList<String>();
		
		Cache cache=null;
		try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
		   e.printStackTrace();
		   
		}
		
		if(cache.containsKey(nameCache))
		{
			list = (ArrayList<String>) cache.get(nameCache);
		}
		
		return list;
	}
	public static ArrayList<NewsRecent> getCacheNews(String nameCache)
	{
		ArrayList<NewsRecent>  list = new ArrayList<NewsRecent>();
		
		Cache cache=null;
		try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
		   e.printStackTrace();
		   
		}
		
		if(cache.containsKey(nameCache))
		{
			list = (ArrayList<NewsRecent>) cache.get(nameCache);
		}
		
		return list;
	}
}
